﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using EvincePayroll.Data;
using EvincePayroll.Utility;
using System.Net;
using System.Text;
using EvinceUI.JQueryDataTable.Model;
using EvinceUI;

namespace EvincePayroll.Controllers
{
    public class PageTemplateController : Controller
    {
        //
        // GET: /PageTemplate/

        public ActionResult Template(string pageId)
        {
            PageTemplateData pageData = null;
            EvincePayrollService pageTemplateService = new EvincePayrollService(ServiceTypes.PageTemplate);
            pageData = pageTemplateService.GetPageTemplate(pageId);
            ViewBag.Template = pageData;
            return View("Template");
        }


        public ActionResult AddPage(string pageId)
        {
            PageTemplateData pageData = null;
            EvincePayrollService pageTemplateService = new EvincePayrollService(ServiceTypes.PageTemplate);
            if(pageId!=null)
            {
                pageData = pageTemplateService.GetPageTemplate(pageId);
            }
           // ViewBag.ParentChild = ws.GetParentChild();
            return View(pageData);
        }
        
        [HttpPost, ValidateInput(false)]
        public ActionResult AddPage(PageTemplateData page, string chksatatus, string Content, string PageID)
        {
            bool pageData;
            if (chksatatus == "on")
            {
                EmployeeData employee = (EmployeeData)Session["EmployeeData"];
                page.Status = 1;
                page.StatusString = "Active";

                EvincePayrollService pageTemplateService = new EvincePayrollService(ServiceTypes.PageTemplate);
                pageData = pageTemplateService.AddPage(page, employee.Email,PageID);
            }
            else if (chksatatus == null)
            {
                page.Status = 0;
                page.StatusString = "Inactive";
                EmployeeData employee = (EmployeeData)Session["EmployeeData"];
                EvincePayrollService pageTemplateService = new EvincePayrollService(ServiceTypes.PageTemplate);
                pageData = pageTemplateService.AddPage(page, employee.Email, PageID);
            }
            return View("ListPage");
        
        }

        public ActionResult ListPage()
        {

            return View();
        }
            

            
        
        

        public ActionResult AjaxGetListPage(JQueryDataTableParamModel param)
        {
            List<PageTemplateData> pageTemplate;
            EmployeeData employee = (EmployeeData)Session["EmployeeData"];
            EvincePayrollService pageTemplateService = new EvincePayrollService(ServiceTypes.PageTemplate);
            pageTemplate = pageTemplateService.GetAllPageList();
            if (pageTemplate != null)
            {
                IEnumerable<PageTemplateData> filteredRequests;

                //Check whether the companies should be filtered by keyword
                if (!string.IsNullOrEmpty(param.sSearch))
                {
                    //Used if particular columns are filtered


                    var DispalyTitleFilter = Convert.ToString(Request["sSearch_2"]);
                    var MetaKeywordFilter = Convert.ToString(Request["sSearch_3"]);
                    

                    






                    //Optionally check whether the columns are searchable at all

                    var isDispalyTitleSearchable = Convert.ToBoolean(Request["bSearchable_2"]);
                    var isMetaKeyword = Convert.ToBoolean(Request["bSearchable_3"]);
                    




                    char[] chars = new char[] { '&', '|' };

                    if (param.sSearch.IndexOfAny(chars) > 0)
                    {
                        string expression = GetExpression(param.sSearch.ToUpper());
                        StringBuilder filter = new StringBuilder();
                        filter.Append("(").Append(expression.Replace("[FIELD]", "DisplayTitle.ToUpper()")).Append(") ||");
                        filter.Append("(").Append(expression.Replace("[FIELD]", "MetaKeywords.ToString().ToUpper()")).Append(")||");

                        filteredRequests = pageTemplate;
                    }
                    else
                    {

                        filteredRequests = pageTemplate
                        .Where(d => isDispalyTitleSearchable && d.DisplayTitle.ToString().Contains(param.sSearch.Trim().ToLower())
                         ||
                        isMetaKeyword && d.MetaKeywords.ToString().ToLower().Contains(param.sSearch.Trim().ToLower())
                        
                       

                        );

                    }
                }
                else
                {
                    filteredRequests = pageTemplate;

                }

                var isDispalyTitle = Convert.ToBoolean(Request["bSortable_2"]);
                var isMetaKeywordtitle = Convert.ToBoolean(Request["bSortable_3"]);
                var isMetaDescription = Convert.ToBoolean(Request["bSortable_4"]);
               




                var sortColumnIndex = Convert.ToInt32(Request["iSortCol_0"]);
                Func<PageTemplateData, string> orderingFunction = (//d => sortColumnIndex == 1 && isEmployeeId ? d.EmployeeStringId.ToString() :
               d => sortColumnIndex == 2 && isDispalyTitle ? d.DisplayTitle.ToString() :
                sortColumnIndex == 3 && isMetaKeywordtitle ? d.MetaKeywords.ToString() :
                sortColumnIndex == 4 && isMetaDescription ? d.MetaDescription.ToString() :
                
                "");

                var sortDirection = Request["sSortDir_0"]; // asc or desc
                if (sortDirection == "asc")
                    filteredRequests = filteredRequests.OrderBy(orderingFunction);
                else
                    filteredRequests = filteredRequests.OrderByDescending(orderingFunction);

                var displayedCompanies = filteredRequests.Skip(param.iDisplayStart).Take(param.iDisplayLength);
                var result = from p in displayedCompanies
                             select new[] {
                            p.PageId.ToString(),
                            p.PageCode,
                            p.DisplayTitle,
                            p.MetaKeywords,
                            p.MetaDescription,
                            GetStatus(p.Status.ToString()),
                            GetEditPage(p.PageId.ToString())
                             
                            // string.Format("<a href=\"#\" onclick=\"updateStatusAccept(this)\" class=\"ApproveStatus\">Approve<input type=\"hidden\" value=\"{0}\" /></a>",Convert.ToString(p.LeaveId))+"/"+
                             //string.Format("<a href=\"#\" onclick=\"updateStatusReject(this)\" class=\"RejectStatus\">Reject<input type=\"hidden\" value=\"{0}\" /></a>",Convert.ToString(p.LeaveId))
                         };

                return Json(new
                {
                    sEcho = param.sEcho,
                    iTotalRecords = pageTemplate.Count(),
                    iTotalDisplayRecords = filteredRequests.Count(),
                    aaData = result
                },
                JsonRequestBehavior.AllowGet);
            }
            else
              return Json(new { }, JsonRequestBehavior.AllowGet);
        }

        public string GetStatus(string status)
        {
            string statusString = string.Empty;
            if (status == "0")
            {
                statusString = string.Format("<label ><span style=\"color:red\">InActive</span></label>");
            }
            else if (status == "1")
            {
                statusString = string.Format("<label><span style=\"color:green\">Active</span></label>");
            }

            return statusString;
        }

        private string GetExpression(string p)
        {
            throw new NotImplementedException();
        }

        public string GetEditPage(string pageId)
        {
            string url = string.Empty;
            url = string.Format("<a href=\"../PageTemplate/AddPage?pageId={0}\"><span>Edit</span></a>&nbsp;<a href=\"#\" onclick=\"DeleteCMS('{1}')\">Delete</a>", pageId,pageId);
            return url;
        }

        public bool DeleteCMS(string pageId)
        {
            bool result=false;
            if (pageId != string.Empty)
            {
                EvincePayrollService pageTemplateService = new EvincePayrollService(ServiceTypes.PageTemplate);
                result = pageTemplateService.DeleteCMS(pageId);
            }
            return result;
        
        }
        
    }
}
